import axios from 'axios'

import * as interfaces from "./Interfaces.json";
import Tracker from "./Tracker";
import Alymodel from '../../mysql_interface/model'

function csrfSafeMethod(method: string) {
  // these HTTP methods do not require CSRF protection
  return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);
}
export function jilurizhi(arr: [string, any][]) {
  // if (process.env.NODE_ENV === 'production') {
  const host = 'cn-qingdao.log.aliyuncs.com';
  const project = 'htetest1';
  const logstore = 'ojhte';
  const log = new Tracker(host, project, logstore);
  log.push('_userid_', window._userid_)
  log.push('_username_', window._username_)
  log.push('_phonenum_', window._phonenum_)
  log.push('_teamids_', window._teamids_)
  log.push('_cid_', window._cid_)

  for (const v of arr) {
    log.push(v[0], v[1])
  }
  log.logger()
  // }
}
// 添加csrf 验证
// 添加日志

interface Iapi<T> {
  error: number,
  msg?: string,
  data: T
}

export type Iobj<T = any> = {
  [key in keyof T]?: any;
} & {
  _limit?: number;
  _offset?: number;
  _order?: keyof T;
  _sortable?: 'DESC' | 'ASC';
  _like?: [keyof T, any] | Array<[keyof T, any]>;
};


export function post<T, R = {}>(input: string, body?: R, method = 'POST') {

  const host = 'cn-qingdao.log.aliyuncs.com';
  const project = 'htetest1';
  const logstore = 'ojhte';
  const t = Date.now()
  const log = new Tracker(host, project, logstore);
  log.push('_userid_', window._userid_)
  log.push('_username_', window._username_)
  log.push('_teams_', window._teams_)
  log.push('_phonenum_', window._phonenum_)
  log.push('_method_', input);
  log.push('_teamids_', window._teamids_)
  log.push('_cid_', window._cid_)
  log.push('type', 'fetch');
  try {
    const d = JSON.stringify(body)
    if (d && d.length < 1000) {
      log.push('body', JSON.stringify(body));
    }
  } catch (e) {
    console.log(e)
  }

  const arr = document.cookie.split(';')
  let csrf = ''
  for (const v in arr) {
    const to = arr[v].split('=');
    if (to[0].replace(/\s+/g, "") === "csrfToken") {
      csrf = to[1].replace(/\s+/g, "")
    }
  }

  if (!window.fetch === false) {
    return new Promise<T>((res, rej) => {
      fetch('/api' + input, {
        cache: 'no-cache',
        headers: {
          'content-type': 'application/json',
          'x-csrf-token': csrf
        },
        method,
        body: JSON.stringify(body)
      }).then(res => {
        log.push('status', res.status);
        log.push('time', Date.now() - t);
        return res.json()
      }).then((body: Iapi<T>) => {
        const { data, error, msg } = body
        if (error) {
          log.push('_error_', error);
          rej(msg)
        } else {
          res(data)
        }
        if (process.env.NODE_ENV === 'production') {
          log.logger()
        }
      }).catch(e => {
        log.push('_error_', e);
        if (process.env.NODE_ENV === 'production') {
          log.logger()
        }
        rej(e)
      })
    })
  } else {
    return new Promise<T>((res, rej) => {
      axios.post('/api' + input, body).then(({ data }) => {
        if (data.error) {
          rej(data.meg)
        } else {
          res(data.data)
        }
      }).catch(() => {
        rej('服务器出错')
      })
    })
  }

}



// ajaxSetup({
//   beforeSend: function (xhr, settings) {
//     if (process.env.NODE_ENV === "production") {
//       const host = "cn-qingdao.log.aliyuncs.com";
//       const project = "htetest1";
//       const logstore = "ojhte";
//       let log = new Tracker(host, project, logstore);
//       log.push('_userid_', window._userid_)
//       log.push('_username_', window._username_)
//       log.push('_phonenum_', window._phonenum_)
//       if (settings.data) {
//         log.push("_params_", settings.data);
//         let data = settings.data.split("&");
//         for (let v in data) {
//           let to = data[v].split("=");
//           if (to[0].replace(/\s+/g, "") === "uid") {
//             log.push("_uid_", to[1]);
//           }
//           if (to[0].replace(/\s+/g, "") === "cid") {
//             log.push("_cid_", to[1]);
//           }
//           if (to[0].replace(/\s+/g, "") === "ips") {
//             log.push("_ip_", to[1]);
//           }
//         }
//       }
//       log.push("_method_", settings.url);
//       log.push("_type_", settings.type);
//       log.push("type", 'fetch');
//       log.push("_error_", xhr.responseJSON && xhr.responseJSON.error);
//       log.push("_topic_", "htewebhome");
//       new Agent(log);
//       log.logger();
//     }

//     if (!csrfSafeMethod(settings.type || '') && !this.crossDomain) {
//       let arr = document.cookie.split(";");
//       for (let v in arr) {
//         let to = arr[v].split("=");
//         if (to[0].replace(/\s+/g, "") === "csrfToken") {
//           xhr.setRequestHeader("x-csrf-token", to[1].replace(/\s+/g, ""));
//         }
//       }
//     }
//   }
// });

export type IMlogin = {
  loginID?: string
  password?: string
  yzm?: string
  phonenumber?: string
}

export const asynclogin = function (data: IMlogin) {
  return post<Alymodel.IMuser>(interfaces.login, data)
};

export const asyncloginphonenum = function (data?: any) {
  return post(interfaces.loginphonenum, data)
};

export const session = async function () {
  const data = await post<Alymodel.IMuser>(interfaces.online, undefined, 'GET')
  window._userid_ = data.userid;
  window._username_ = data.username;
  window._phonenum_ = data.phonenum
  window._teamids_ = data.teamids
  window._cid_ = data.cardid
  return data
};

export const getallcourse = function (data?: any) {

  return post<Alymodel.IMcourse[]>(interfaces.AllCourse, data)


};


// 提交答案
export const asynccheckQuestion = function (data?: any) {

  return post(interfaces.checkQuestion, data)


};

// 创建学生

export const asyncnewstudent = function (data?: any) {

  return post(interfaces.newStudent, data)


};

// 获取视频信息

export const asyncgetvideoInfo = function (data?: any) {

  return post(interfaces.videoInfo, data)


};

// 通过course id 获取 lession
export const asyncgetLessionByCourseid = function (data?: { cid: number }) {

  return post<[Alymodel.IMlession]>(interfaces.getLessionByCourseid, data)


};

// 获取用户课程

export const asyncgetktUser = function (data?: any) {

  return post<Alymodel.IMcourse[]>(interfaces.getCourse, data)


};

// 获取推荐课程

export const asyncgetTuijian = function (data?: any) {

  return post(interfaces.AllCourse, data)


};

// 获取课堂信息
export const asyncgetktById = function (data?: any) {

  return post(interfaces.CourseInfo, data)


};

export const asyncupdate = function (data?: any) {

  return post(interfaces.update, data)


};

// 支付宝接口
// export const asyncpay = function (data) {
//   
//     return post(interfaces.pay, data, "text")


//   });
// };

// 重置密码

export const asyncchangePassword = function (data?: any) {

  return post(interfaces.changePassword, data)


};

export const asyncUserCourseInfo = function (data?: any) {
  return post(interfaces.UserCourseInfo, data)
};

export const asyncgetLessionByCourseidAndNum = function (data?: any) {

  return post(interfaces.getLessionByCourseidAndNum, data)


};

// 刷新用户学到第几节
export const asynclearn = function (data?: any) {

  return post(interfaces.learn, data)


};

// 获取支付宝支付接口
export const asynpay = function (data?: any) {

  return post(interfaces.pay, data)


};

// 添加收藏
export const asynaddCollection = function (data?: any) {

  return post(interfaces.addCollection, data)


};

// 用户注册
export const asyncregist = function (data?: any) {

  return post(interfaces.regist, data)


};

// 获取子用户
export const asyncgetChildren = function (data?: any) {

  return post(interfaces.getChildren, data)


};

// 获取课程包
export const asyncgetInvite = function (data?: any) {

  return post(interfaces.getInvite, data)


};

// 审核子用户
export const asynccheckUser = function (data?: any) {

  return post(interfaces.checkUser, data)


};

export const asyncgetCourseFile = function (data?: any) {

  return post<Alymodel.Ifileurl[]>(interfaces.getCourseFile, data)


};

// 获取yzm
export const asyncfind_getCode = function (data?: any) {

  return post(interfaces.find_getCode, data)


};

// 检查yzm
export const asyncfind_checkCode = function (data?: any) {

  return post(interfaces.find_checkCode, data)


};

// 修改密码
export const asyncfind_findPassword = function (data?: any) {

  return post(interfaces.find_findPassword, data)


};

// 注册获取yzm
export const asyncregist_getCode = function (data?: any) {

  return post(interfaces.regist_getCode, data)


};

// 获取微信支付
export const asyncWXpay = function (data?: any) {

  return post(interfaces.WXpay, data)


};

// 站内信
// 创建消息
export const asyncnewMessage = function (data?: any) {

  return post(interfaces.newMessage, data)


};

// 查询收到消息
export const asyncreceivedMessage = function (data?: any) {

  return post(interfaces.receivedMessage, data)


};

// 查询发送消息
export const asyncsentMessage = function (data?: any) {

  return post(interfaces.sentMessage, data)


};

// 标记消息已读
export const asyncreadMessage = function (data?: any) {

  return post(interfaces.readMessage, data)


};

// 获取视频列表
export const asyncGetVideoList = function (data?: any) {

  return post(interfaces.GetVideoList, data)


};

// 修改视频
export const asyncupdateVideoInfo = function (data?: any) {

  return post(interfaces.updateVideoInfo, data)


};

// 删除视频
export const asyncdeleteVideo = function (data?: any) {

  return post(interfaces.deleteVideo, data)


};

// 通过lid获取视频信息

export const asyncgetVideoIDByLessionID = function (data?: any) {

  return post(interfaces.getVideoIDByLessionID, data)


};
export const asyncgetlessions = function (data?: any) {

  return post(interfaces.getlessions, data)


};

// wx获取验证码
export const asyncgetLoginQRCode = function (data?: any) {

  return post(interfaces.getLoginQRCode, data)


};

// wx绑定
export const asyncgetBindQRCode = function (data?: any) {

  return post(interfaces.getBindQRCode, data)


};

// // wxWXBindPhone
// export const asyncWXBindPhone = function (data) {
//   
//     return post(interfaces.WXBindPhone).then(response => {
//       if (response.error == 0) {
//         resolve(response.data)
//       } else {
//         reject(response.msg)
//       }
//     }).catch(function (error) {
//       console.log(error);
//       reject('服务器开小差了')
//     })
//   })
// }

// // wxbindWXBindUser
// export const asyncWXBindUser = function (data) {
//   
//     return post(interfaces.WXBindUser).then(response => {
//       if (response.error == 0) {
//         resolve(response.data)
//       } else {
//         reject(response.msg)
//       }
//     }).catch(function (error) {
//       console.log(error);
//       reject('服务器开小差了')
//     })
//   })
// }

// WXAuthorize
export const asyncWXAuthorize = function (data?: any) {
  return post(interfaces.WXAuthorize, data)
};

// 免费课程
export const asyncForfeepay = function (data?: any) {

  return post(interfaces.Forfeepay, data)


};

// 查询用户积分
export const asyncgetUserAllPoint = function (data?: any) {

  return post(interfaces.getUserAllPoint, data)


};

// 查询某个用户的类别分
export const asyncgetuserTypePoint = function (data?: any) {

  return post(interfaces.getUserTypePoint, data)


};

// 查询课程资料
export const asyncselectCoursefile = function (data?: any) {

  return post<Alymodel.Iteachercoursefile[]>(interfaces.selectCoursefile, data)


};

// 查询视频调整
export const asyncselectWhitepoint = function (data?: any) {

  return post(interfaces.selectWhitepoint, data)


};


//课程打包
//显示所有的课程组
export const showbag = function (data?: any) {

  return post(interfaces.showbag, data)


};

//从课程封面点击进去查看内部课程
export const selectcoursebybid = function (data?: any) {

  return post(interfaces.selectcoursebybid, data)


};

//绑定微信
export const bindwechat = function (data?: any) {
  return post(interfaces.bindwechat, data)
};

//获取所有课程组
export const getAllCatebag = function (data?: any) {
  return post<Alymodel.IMcatebag[]>(interfaces.getAllCatebag, data)
};

// 获取该课程组下的所有课程
export const getCourseByCatabagid = function (data?: any) {
  return post(interfaces.getCourseByCatabagid, data)
};

// 获取iframe
export const asyncgetiframebyid = function (data?: any) {

  return post(interfaces.getiframebyid, data)


};

// 获取iframe
export const asyncgetiframebycourseid = function (data?: any) {

  return post(interfaces.getiframebycourseid, data)


};

// 获取getCoursecountByCatabagid 数量
export const asyncgetCoursecountByCatabagid = function (data?: any) {

  return post(interfaces.getCoursecountByCatabagid, data)


};

// 通过id获取课程组
export const asyncgetcatebagsbyid = function (data?: any) {

  return post(interfaces.getcatebagsbyid, data)


};

//获取所有课程组类型
export const getAllCatebagtype = function (data?: any) {

  return post<Alymodel.IMcatebagtype[]>(interfaces.getAllCatebagtype, data)


};

export const asyncgetuserUsercourse = function (data?: any) {

  return post<Alymodel.IMusercourse[]>(interfaces.getuserUsercourse, data)


};

export const wechatsignature = function (data?: any) {

  return post(interfaces.wechatsignature, data)


};


export const asyncforum = function (data?: any) {

  return post(interfaces.forum, data)


};

export const asynccreatetopic = function (data?: any) {

  return post(interfaces.createtopic, data)


};

export const asyncupdatetopic = function (data?: any) {

  return post(interfaces.updatetopic, data)


};

export const asyncdelecttopicbyid = function (data?: any) {

  return post(interfaces.delecttopicbyid, data)


};

export const asyncgettopicbyid = function (data?: any) {

  return post(interfaces.gettopicbyid, data)


};

export const asyncgettopicbyuser = function (data?: any) {

  return post(interfaces.gettopicbyuser, data)


};

export const asyncgettopic = function (data?: any) {

  return post(interfaces.gettopic, data)


};

export const asyncgetreply = function (data?: any) {

  return post(interfaces.getreply, data)


};

export const asynccreatereply = function (data?: any) {

  return post(interfaces.createreply, data)


};

export const asynctopiccount = function (data?: any) {

  return post(interfaces.topiccount, data)


};

export const asynccreatetopiccollect = function (data?: any) {

  return post(interfaces.createtopiccollect, data)


};

export const asyncgettopiccollectbyuser = function (data?: any) {

  return post(interfaces.gettopiccollectbyuser, data)


};

export const asyncgetusercollect = function (data?: any) {

  return post(interfaces.getusercollect, data)


};

export const asyncgetuserreply = function (data?: any) {

  return post(interfaces.getuserreply, data)


};

export const asyncgetuserreplyfabulous = function (data?: any) {

  return post(interfaces.getuserreplyfabulous, data)


};

export const asyncgetusertopic = function (data?: any) {

  return post(interfaces.getusertopic, data)


};

export const asynccreaterepcyfabulous = function (data?: any) {

  return post(interfaces.createrepcyfabulous, data)


};

//创建作品
export const asynccreateshare = function (data?: any) {

  return post(interfaces.createshare, data)


};
//修改作品
export const asyncupdateshare = function (data?: any) {

  return post(interfaces.updateshare, data)


};
//通过id删除作品
export const asyncdelectsharebyid = function (data?: any) {

  return post(interfaces.delectsharebyid, data)


};
//通过id获取作品
export const asyncgetsharebyid = function (data?: any) {

  return post(interfaces.getsharebyid, data)


};
//获取自己所有作品
export const asyncgetsharebyuser = function (data?: any) {

  return post(interfaces.getsharebyuser, data)


};
//获取所有已审核的作品
export const asyncgetshare = function (data?: any) {

  return post(interfaces.getshare, data)


};
//给作品点赞或者取消
export const asynccreatesharefabulous = function (data?: any) {

  return post(interfaces.createsharefabulous, data)


};
//通过id获取作品已经点赞
export const asyncgetsharefabulousbyid = function (data?: any) {

  return post(interfaces.getsharefabulousbyid, data)


};
//创建作品评论
export const asynccreatesharecomment = function (data?: any) {

  return post(interfaces.createsharecomment, data)


};
//通过id删除作品评论
export const asyncdelectsharecommentbyid = function (data?: any) {

  return post(interfaces.delectsharecommentbyid, data)


};
//通过id获取评论
export const asyncgetsharecomment = function (data?: any) {

  return post(interfaces.getsharecomment, data)


};
//给评论点赞或者取消
export const asynccreatesharecommentfabulous = function (data?: any) {

  return post(interfaces.createsharecommentfabulous, data)


};
//获取评论是否点赞
export const asyncgetsharecommentfabulousbyid = function (data?: any) {

  return post(interfaces.getsharecommentfabulousbyid, data)


};
//上传权限
export const asyncossupload = function (data?: any) {

  return post(interfaces.ossupload, data)


};

//获取作品数量
export const asyncgetsharecount = function (data?: any) {

  return post(interfaces.getsharecount, data)


};

// 查询所有课程包课程
export const asyncgetcoursecatebag = function (data?: any) {

  return post<Alymodel.IMcoursecatebag[]>(interfaces.getcoursecatebag, data)


};

// 上传新用户信息
export const asyncbindwechatpasswold = function (data?: any) {

  return post(interfaces.asyncbindwechatpasswold, data)


};
// 修改个人信息
export const update = function (data?: any) {
  return post(interfaces.update, data)
};


export const asyncossupload8 = function (data?: any) {
  return post<any>(interfaces.ossupload8, data)
};
export const asyncInquireusertotpdataid9 = function (data?: any) {
  return post<any>(interfaces.Inquireusertotpdataid9, data)
};

export const asyncvideoQuestion = function (data?: any) {
  return post<Alymodel.Ivideoquestion[]>(interfaces.videoQuestion, data)
};

export const asyncdelwxopid = function (data?: any) {
  return post(interfaces.delwxopid, data)
};

export interface Imyreq<T> {
  count: number;
  rows: T[];
}

export const asyncselectcourseforum = function (data: Iobj<Alymodel.IMcourseforum>) {
  return post<Imyreq<Alymodel.IMcourseforum>>(interfaces.selectcourseforum, data)
}


export const asynccreatedcourseforum = function (data: Alymodel.IMcourseforum & { catebag: string, coursename: string, userphonenum: string }) {
  return post(interfaces.createdcourseforum, data)
}

export const asyncdelcourseforum = function (data: { ID: number }) {
  return post(interfaces.delcourseforum, data)
}

export const asynclogout = function () {
  return post(interfaces.logout)
}